// packageA/mycomponent/goodsComponent/foot/foot.js
const DrainageScene = require('../../../../utils/drainage_scene.js')

const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    ipnonexbol: {
      type: null,
    },
    goodsType: {
      type: null,
    },
    goods_plugin: {
      type: null,
    },
    activityid: {
      type: null,
    },
    isBegTime: {
      type: null,
    },
    isRent: {
      type: null,
    },
    isTime: {
      type: null,
    },
    beginDownObj: {
      type: null,
    },
    goodsId: {
      type: Number,
    },
    enterAt: {
      type: Object,
    },
    goodsInfo: {
      type: null,
    },
    isTimeEnd: {
      type: null,
    },
    leader_partake: {
      type: null,
    },
    leader_not_join_invalid: {
      type: null,
    },
    mode: {
      type: null,
    },
    cart_num: {
      // 购物车数量
      type: null,
    },
    debtId: {
      // 置换亿栈店铺id
      type: null
    },
    MachineId:{ //自动售货机id
      type:null
    }
  },

  /**
   * 组件的初始数据
   */
  data: {

    tiktok_popup:false,
    posterShow:false,

    isDisabled: false, //是否禁用立即购买
    // 拼团
    group_price: "",
    // 客服
    service_mobile: "",
    service_QRcode: "",
    customer_open: false,
    show1: false,
    isAddCart: false,
    SUBMIT_ACTION_CART: "-1", //添加到购物车
    SUBMIT_ACTION_BUY: "-2", //立即购买
    specsManage: [],
    goodsCount: 1,
    language: "",
    beginDownObj: {
      day: "00",
      hou: "00",
      min: "00",
      sec: "00",
    },
    is_yz_supplyGoods: false,
    gooddatas: [],
    //是否显示购物车
    nocart: false,
    //限时购开关
    isBuy: false,
    goods_info: [],
    timestamp: Date.parse(new Date()) / 1000,
    checkSetTimeOut: '',
    isShowShop: true, //是否显示首页or店铺入口
    AdressState:'1',//2无货禁用，1有货
    supplierListShow:false,
    isDisabledText: '立即购买',
    isShowAddCartBtn: true,//是否显示加入购物车按钮
    yz_supply_lease:false,
    isShowtemplateCode03: false,//详情模板3，固定联系电话和客服
  },
  observers: {
    "goodsInfo,goodsType": function (info, type) {
      if (type != "group_goods" && type != "grabGroup"&& type != "ywmGroup") {
        this.setIsAddCart();
        if (type == "hotelGoods") {
          this.isFavorite();
        }
        if (info?.plugin_id == 140) {
          this.setSupplyGoodsData();
        }
        if (info?.plugin_id == 164) {
          this.setYzSupplyLease();
        }
        if (info.supplier && Number(info.supplier.is_open) == 0) {
          this.setData({
            isShowShop: false
          });
        }
      }
    },
    "goods_plugin":function(nval,oval){
      this.setData({
        yz_supply_lease:nval?.yz_supply_lease?.is_yz_supply_lease == 1?true:false
      })
    }
  },
  lifetimes: {
    attached() {
      let language = wx.getStorageSync("langIndex");
      this.setData({
        language: language.en,
      });
      this.setSupplyGoodsData();
      this.basic_info = wx.getStorageSync("yz_basic_info");
      if (this.basic_info) {
        if (this.basic_info.home.item.ViewSet?.goods?.code == "goods03") {
          this.setData({
            isShowtemplateCode03: true,
            nocart: true
          });
        }
      }
    },
    ready() {
      if (this.data.goodsType == 'zhpGroup') {
        this.checkSet();
      }
      this.setGoodBuyDisabled();
      if(this.data.MachineId){
        this.setData({nocart:true})
      }
    },
    detached() {
      if (this.data.goodsType == 'zhpGroup') {
        clearInterval(this.data.checkSetTimeOut);
      }
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    
    toMyGroups(){
      wx.navigateTo({
        url: '/packageB/member/group/MyGroups/MyGroups',
      })
    },
    childAdressPost(e) {
      this.setData({
        AdressState: e
      })
    },
    closeShopList(){
      this.setData({
        supplierListShow:false
      })
    },
    setGoodBuyDisabled() {
      let goods_plugin = this.data.goods_plugin;
      if (goods_plugin && goods_plugin.month_buy_limit && goods_plugin.month_buy_limit != [] && goods_plugin.month_buy_limit.hasOwnProperty('can_buy')) {
        // 海诚-商品分类会员等级限购#89586
        this.setData({
          isDisabled: !goods_plugin.month_buy_limit.can_buy
        })
      }

      if (this.data.goodsInfo?.buy_limit?.status == 1 && this.data.goodsInfo?.buy_limit?.end_time == 0 ) {
        // 限时购时间段
        this.setData({
          isDisabled: true,
          isDisabledText: '暂不可购买',
          isShowAddCartBtn: false
        })
      }
    },
    setYzSupplyLease(){
      let plugin_setting = wx.getStorageSync("yz_basic_info").plugin_setting;
      if(plugin_setting?.yz_supply_lease?.is_ios_sell == '1') {
        let res = wx.getSystemInfoSync();
        if( res.platform == 'ios' && this.data.goodsInfo?.plugin_id == 164 ){
          this.setData({
            isDisabled:true
          })
        }
      }
    },
    setSupplyGoodsData() {
      let plugin_setting = wx.getStorageSync("yz_basic_info").plugin_setting;
      if (plugin_setting && plugin_setting.yz_supply_camilo_resources && (plugin_setting.yz_supply_camilo_resources.is_ios_sell === 1 || plugin_setting.yz_supply_camilo_resources.is_ios_sell === '1')) {
        let res = wx.getSystemInfoSync();
        if (res.platform == 'ios' && this.data.goodsInfo?.plugin_id == 140) {
          this.setData({
            is_yz_supplyGoods: true
          });
        }
      }
    },
    originalPriceTo(e) {
      let gid = e.currentTarget.dataset.gid;
      wx.navigateTo({
        url: '/packageA/detail_v2/detail_v2?id=' + gid,
      })
    },
    gotoChat(evt) {
      let url = evt.currentTarget.dataset.cservice + "&goods_id=" + this.data.goodsId;
      console.log(url);
      wx.navigateTo({
        url: url,
        fail: (err) => {
          app.tips("客服路由出错");
        }
      });
    },
    gotoCart1() {
      wx.reLaunch({
        url: "/packageG/pages/buy/cart_v2/cart_v2",
      });
    },
    gotoindex() {
      wx.reLaunch({
        url: "/packageG/index/index",
      });
    },
    tapkefu() {
      this.setData({
        kefu: true,
      });
    },
    closePop() {
      this.setData({
        show1: false,
      });
    },
    showPop() {
      console.log('执行');
      let setServicePlugin = app._isTextEmpty(this.data.service_mobile) && app._isTextEmpty(this.data.service_QRcode);
      if (app._isTextEmpty(this.data.cservice) && setServicePlugin) {
        return app.tips("抱歉，暂未设置客服信息");
      }
      if (!app._isTextEmpty(this.data.cservice) && setServicePlugin) {
        this.gotoChat({
          currentTarget: {
            dataset: {
              cservice: this.data.cservice
            }
          }
        }) //只设置了客服链接，直接跳转
        return;
      }
      this.setData({
        show1: true,
      });
    },
    callPhone() {
      wx.makePhoneCall({
        phoneNumber: this.data.service_mobile,
      });
    },
    //判断是否能加入购物车
    setIsAddCart() {
      //为空是老数据默认值问题
      if (app._isTextEmpty(this.data.goodsInfo.buy_way) || this.data.goodsInfo.buy_way == "0") {
        this.setData({
          isAddCart: true,
        });
      }
      //不能加入 金币产品
      if (this.data.goodsInfo.buy_way == 1) {
        this.setData({
          isAddCart: false,
        });
      }
    },
    // 加入购物车
    addCart() {
      // this.triggerEvent('addCartFoot')
      let that = this;
      if (!this.data.isAddCart) {
        return;
      }
      //价格权限
      if (this.data.goodsInfo.vip_level_status && this.data.goodsInfo.vip_level_status.status == 1) {
        wx.showToast({
          icon: "none",
          title: this.data.goodsInfo.vip_level_status.tips,
          duration: 2500,
        });
        return;
      }
      let urlStr = app.getNetAddresss("member.member.isValidatePageGoods");
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            if (that.data.goodsInfo.has_one_invite_page && that.data.goodsInfo.has_one_invite_page.status === 1 && res.data.is_invite === 0) {
              wx.navigateTo({
                url: "/packageC/member/visit/Inviter/Inviter?fromGood=" + 1,
              });
              return;
            }
            that.setData({
              submitActionTag: that.data.SUBMIT_ACTION_CART,
            });
            that.triggerEvent("popupModeshowChild", {
              submitActionTag: that.data.SUBMIT_ACTION_CART,
            });
            //判断是否有规格
            if (that.data.goodsInfo.has_option == 1) {
              console.log("1111111111111111111", that.data.optionsId);
              that.triggerEvent("popupModeshowChild", {
                popupSpecs: true,
                popupModeshow: false,
                submitActionTag: that.data.SUBMIT_ACTION_CART,
              });
            } else {
              console.log("1111111111111111111加入购物车操作，无规格");
              //处理参数 无规格
              that.setData({
                optionsId: "",
              });
              if (that.data.isAddCart) {
                console.log(that.data.SUBMIT_ACTION_CART);
                that.triggerEvent("popupModeshowChild", {
                  popupSpecs2: true,
                  popupModeshow: false,
                  submitActionTag: that.data.SUBMIT_ACTION_CART,
                  isAddCart: that.data.isAddCart
                });
              }

              // that.addCartRequest(that.data.goodsId, that.data.optionsId, that.data.goodsCount);
            }
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 2500,
            });
          }
        },
      });
    },

    //******************** 加入购物车网络操作 ***************
    addCartRequest(_goodsId, _optionsId, _total) {
      //库存不足
      if (this.data.optionsMaxCount == 0) {
        wx.showToast({
          icon: "none",
          title: "商品库存不足",
          duration: 2500,
        });
        return;
      }
      if (_total <= 0) {
        this.setData({
          popupSpecs: false,
          popupModeshow: true,
        });
        wx.showToast({
          icon: "none",
          title: "请选择商品数量",
          duration: 2500,
        });
        return;
      }

      let that = this;
      let goods = [];
      goods.push(_goodsId);
      let urlStr = app.getNetAddresss("from.div-from.isDisplay");
      urlStr += "&goods_ids=" + JSON.stringify(goods);
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            // var _data = res.data;
            if (res.data.status && !res.data.member_status) {
              wx.showModal({
                title: "提示",
                content: "购买此商品,请补充您的个人信息",
                success(res) {
                  if (res.confirm) {
                    //保税真实信息添加
                    wx.navigateTo({
                      url: "/packageB/member/address/myinfo/myinfo?tag=delta",
                    });
                  } else if (res.cancel) {
                    console.log("用户点击取消");
                  }
                },
              });
            } else {
              that.addCartReq(_goodsId, _optionsId, _total);
            }
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 2500,
            });
          }
        },
        fail: function (res) {},
      });
    },
    addCartReq(_goodsId, _optionsId, _total) {
      // let that = this;
      let urlStr = app.getNetAddresss("member.member-cart.store");
      urlStr += "&goods_id=" + _goodsId;
      urlStr += "&total=" + _total;
      urlStr += "&option_id=" + _optionsId;
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            app.globalData.cart_num = res.data.cart_num;
            this.triggerEvent('changeCartNumber', res.data.cart_num);
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 2500,
            });
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 2500,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    // *********************** 加入购物车网络操作end ****************
    toWarning() {
      wx.showModal({
        title: '提示',
        content: '因平台规则限制，IOS端不支持购买虚拟商品；如需帮助，请联系客服。',
        confirmText: "联系客服",
        success: (res) => {
          if (res.confirm) {
            this.showPop();
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    },
    checkPrice_difference_pool(basic_info){
      let urlStr = app.getNetAddresss("plugin.price-difference-pool.frontend.modules.pool.controllers.validate.index");
      return new Promise((resolve, reject) => {
        app._getNetWork({
          showToastIn: false,
          url: urlStr,
          success: (resdata)=> {
            var res = resdata.data;
            if (res.result == 1) {
              resolve(true)
            } else {
              wx.showModal({
                title: '',
                content: `${basic_info.price_difference_pool_name}为负数，请充值后再购买`,
                confirmText:`去${basic_info.price_difference_pool_name}`,
                confirmColor:'#F15353',
                complete: (res) => {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: '/packageJ/priceDifferencePool/index',
                    })
                  }
                }
              })
            }
          },
          fail:()=>{
            reject()
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 2500,
            });
          }
        });
      })
    },
    // 立即购买
    async buyNow(e) {
      let isBindDrainageScene = DrainageScene.bindDrainageScene({
        scene: 1,
        title: this.data.goodsInfo.title,
        goods_id: this.data.goodsId
      });
      if(!isBindDrainageScene) return;//爆客码绑定场景

      if (this.data.is_yz_supplyGoods) {
        this.toWarning();
        return;
      }
      if (this.data.isDisabled) return;
      // this.triggerEvent('  ');
      let key = e ? e : false;
      let that = this;
      if (this.data.isBuy && this.data.isBegTime) {
        wx.showToast({
          icon: "none",
          title: "该商品还没到购买时间",
          duration: 2500,
        });
        return false;
      }
      //价格权限
      if (this.data.goodsInfo.vip_level_status && this.data.goodsInfo.vip_level_status.status == 1) {
        wx.showToast({
          icon: "none",
          title: this.data.goodsInfo.vip_level_status.tips,
          duration: 2500,
        });
        return;
      }
      let basic_info = wx.getStorageSync("yz_basic_info");
      if(basic_info.price_difference_pool){
        if(await this.checkPrice_difference_pool(basic_info) == false){
          return
        }
      }
      let urlStr = app.getNetAddresss("member.member.isValidatePageGoods");
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            if (that.data.goodsInfo.has_one_invite_page && that.data.goodsInfo.has_one_invite_page.status === 1 && res.data.is_invite === 0) {
              wx.navigateTo({
                url: "/packageC/member/visit/Inviter/Inviter?fromGood=" + 1,
              });
              return;
            }
            that.setData({
              submitActionTag: that.data.SUBMIT_ACTION_BUY,
            });
            console.log(that.data.SUBMIT_ACTION_BUY);
            that.triggerEvent("buyNowFoot", {
              submitActionTag: that.data.SUBMIT_ACTION_BUY,
              submitTag: key
            });
            if (that.data.goodsInfo.has_option == 1) {
              //有规格 但是还未选择
              that.setData({
                popupSpecs: true,
                popupModeshow: false,
              });
              that.triggerEvent("buyNowFoot", {
                popupSpecs: true,
                popupModeshow: false,
                submitActionTag: that.data.SUBMIT_ACTION_BUY,
                submitTag: key
              });
            } else if (that.data.goodsInfo.has_option == 0) {
              that.showPopView2();
            }
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 2500,
            });
          }
        },
      });
    },
    showPopView(e) {
      let isa = e.currentTarget.dataset.type;
      this.triggerEvent("buyNowFoot", {
        isAward: isa,
        popupSpecs: true,
        popupModeshow: false,
      });
    },
    showPopView2(buyType) {
      this.triggerEvent("buyNowFoot", {
        popupSpecs2: true,
        popupModeshow: false,
        submitActionTag: this.data.SUBMIT_ACTION_BUY,
      });
    },
    // *************************酒店*******************
    onFavorite(e) {
      let favorite = e.currentTarget.dataset.fadata;
      favorite ? this.removeFavorite() : this.addFavorite();
    },
    //判断是否收藏
    isFavorite() {
      let that = this;
      let urlStr = app.getNetAddresss("member.member-favorite.isFavorite");
      urlStr += "&goods_id=" + this.data.goodsId;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              favorite: res.data.status == 1 ? true : false,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    //移除收藏
    removeFavorite() {
      let that = this;
      let urlStr = app.getNetAddresss("member.member-favorite.destroy");
      urlStr += "&goods_id=" + this.data.goodsId;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              favorite: false,
            });
            wx.showToast({
              icon: "none",
              title: "操作成功",
              duration: 2500,
            });
          } // else {

          //}
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    //添加收藏
    addFavorite() {
      let that = this;
      let urlStr = app.getNetAddresss("member.member-favorite.store");
      urlStr += "&goods_id=" + this.data.goodsId;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              favorite: true,
            });
            wx.showToast({
              icon: "none",
              title: "操作成功",
              duration: 2500,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    // 酒店下单
    order() {
      let gid = this.data.goods_info.get_hotel_info.goods.hotel_id;
      let end = this.data.enterAt ? this.data.enterAt.end : "";
      let start = this.data.enterAt ? this.data.enterAt.start : "";
      wx.navigateTo({
        url: "/packageA/hotel/HotelGoodsOrder/HotelGoodsOrder?end=" + end + "&start=" + start + "&id=" + gid + "&goods_id=" + this.data.goodsId,
      });
    },
    // *************************  酒店end   *******************

    // ******************************    拼团 ******************************
    closeShopList(){
      this.setData({
        supplierListShow:false
      })
    },
    // 跳转主页
    gotoHome(e) {
      let str = e.currentTarget.dataset.str;
      if (str == 'zhplis') {
        console.log('珍惠拼 拼团列表');
        wx.navigateTo({
          url: '/packageB/member/group/MyGroups/MyGroups?types=zhpGroup'
        });
        return;
      }
      if (str == 'supplier' && this.data.goodsInfo.supplier) {
        // wx.navigateTo({
        //   url: "/packageA/member/supplier/SupplierShop/SupplierShop?id=" + this.data.goodsInfo.supplier.id,
        // });
        this.setData({
          supplierListShow:true
        })
        return;
      }
      if(this.data.MachineId){
       wx.reLaunch({
         url: '/packageI/vending_machine/vending_machine?id='+this.data.MachineId,
       })
       return;
      }

      wx.reLaunch({
        url: "/packageG/index/index",
      });
    },
    showGroupMore() {
      let isBindDrainageScene = DrainageScene.bindDrainageScene({
        scene: 8,
        title: this.data.goodsInfo.title
      });
      if(!isBindDrainageScene) return;//爆客码绑定场景

      this.triggerEvent("showGroupMoreChild");
    },
    openCardGroup(){
      this.triggerEvent("buyNowFoot", {
        popupSpecs: true,
        popupModeshow: false,
        submitActionTag: 'openCardGroup'
      });
    },
    tapshowOne() {
      let isBindDrainageScene = DrainageScene.bindDrainageScene({
        scene: 8,
        title: this.data.goodsInfo.title
      });
      if(!isBindDrainageScene) return;//爆客码绑定场景

      this.triggerEvent("buyNowFoot", {
        popupSpecs: true,
        popupModeshow: false,
        submitActionTag: '-2'
      });
    },
    // 新零售
    buyNowRetail(e) {
      let that = this;
      let buyType = e.currentTarget.dataset.buytype;
      if (that.data.goodsInfo.has_option == 1) {
        //有规格 但是还未选择
        that.setData({
          popupSpecs: true,
          popupModeshow: false,
        });
        that.triggerEvent("buyNowRetail", {
          popupSpecs: true,
          popupModeshow: false,
          buyType: buyType,
        });
      } else if (that.data.goodsInfo.has_option == 0) {
        that.showPopVie(buyType);
      }
    },
    showPopVie(buyType) {
      this.triggerEvent("buyNowRetail", {
        popupSpecs2: true,
        popupModeshow: false,
        buyType: buyType
      });
    },

    // 珍惠拼 拼团
    zhpGroupTap(e) {
      console.log(e);
      if (e.currentTarget.dataset.buytype == 'zhpyh') {
        wx.navigateTo({
          url: '/packageB/member/group/MyGroups/MyGroups?tag=1&types=zhpGroup'
        });
        return;
      }
      let that = this;
      if (that.data.goodsInfo.has_option == 1) {
        //有规格 但是还未选择
        that.setData({
          popupSpecs: true,
          popupModeshow: false,
        });
        that.triggerEvent("buyNowFoot", {
          popupSpecs: true,
          popupModeshow: false,
          submitActionTag: that.data.SUBMIT_ACTION_BUY,
          optionsId: that.data.gooddatas.has_many_options[0].option_id
        });
      } else if (that.data.goodsInfo.has_option == 0) {
        that.showPopView2();
      }
    },
    checkSet(num) {
      let that = this;
      let timestamp = this.data.timestamp;
      that.setData({
        timeset: false
      });
      this.data.checkSetTimeOut = setInterval(() => {
        // timestamp = timestamp + 1;
        // console.log(timestamp , that.data.gooddatas.start_time)
        if (this.data.gooddatas.status == 2) {
          that.setData({
            timeset: true
          });
          clearInterval(this.data.checkSetTimeOut);
        }
        if (timestamp <= that.data.gooddatas.start_time) {
          // 小于等于开始时间 活动未开始
          that.setData({
            timeset: true
          });
        } else if (timestamp <= that.data.gooddatas.end_time) {
          // 小于等于结束时间 活动进行中
          that.setData({
            timeset: false
          });
          clearInterval(this.data.checkSetTimeOut);
        }
      }, 1000);
    },
    callPhone() {
      if(!this.data.goodsInfo.contact_tel) {
        wx.showToast({
          icon: "none",
          title: "抱歉，暂无设置联系电话",
          duration: 1500,
        });
        return
      }  
      wx.makePhoneCall({
        phoneNumber: this.data.goodsInfo.contact_tel,
      });
    },
  },
});